//
//  DDDExpressCusDrawVC.m
//  DDDDemo
//
//  Created by mu on 2020/3/3.
//  Copyright © 2020 summer. All rights reserved.
//

#import "DDDExpressCusDrawVC.h"
#import "DDDDrawBaseTableViewCell.h"
//#import "DDDNativeExpressAdManager.h"
#import <DDDAdSdk/DDDNativeExpressAdManager.h>

@interface DDDExpressCusDrawVC ()<UITableViewDataSource, UITableViewDelegate,DDDNativeExpressAdViewDelegate>

@property (strong, nonatomic) UITableView *tableView;
@property (nonatomic, copy) NSArray *dataSource;
@property (nonatomic, strong) DDDNativeExpressAdManager *nativeExpressAdManager;
@property (nonatomic ,strong) DDDDrawBaseTableViewCell *lastCell;

@end

@implementation DDDExpressCusDrawVC

- (void)dealloc {
    _tableView.delegate = nil;
}

- (BOOL)prefersStatusBarHidden {
    return YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView = [[UITableView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.pagingEnabled = YES;
    #if defined(__IPHONE_11_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_11_0
        if ([self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
            if (@available(iOS 11.0, *)) {
                self.tableView.estimatedRowHeight = 0;
                self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            }
        }
    #else
        self.automaticallyAdjustsScrollViewInsets = NO;
    #endif
    [self.view addSubview:self.tableView];
        
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"DDDNativeExpressCell"];
    [self.tableView registerClass:[DDDDrawNormalTableViewCell class] forCellReuseIdentifier:@"DDDDrawNormalTableViewCell"];
    [self.tableView registerClass:[DDDDrawBaseTableViewCell class] forCellReuseIdentifier:@"DDDDrawBaseTableViewCell"];
    
    NSMutableArray *datas = [NSMutableArray array];
    for (NSInteger i =0 ; i <= 15; i++) {
        [datas addObject:@"App tableViewcell"];
    }
    self.dataSource = [datas copy];
    
    [self.tableView reloadData];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(13, 34, 30, 30);
    [btn setImage:[UIImage imageNamed:@"draw_back.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(closeVC) forControlEvents:UIControlEventTouchUpInside];
    [self.view bringSubviewToFront:btn];
    [self.view addSubview:btn];
    btn.accessibilityIdentifier = @"draw_back";
    
    [self loadData];
}

- (void)loadData {
    
    if (!self.nativeExpressAdManager) {
        DDDNativeExpressAdManager *nativeExpressAdManager = [[DDDNativeExpressAdManager alloc] initWithAdSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) andUserID:@"121212"];
        nativeExpressAdManager.delegate = self;
        [nativeExpressAdManager loadAd:3];
        self.nativeExpressAdManager = nativeExpressAdManager;
    } else {
        [self.nativeExpressAdManager loadAd:3];
    }
}

- (void)closeVC{
    [self dismissViewControllerAnimated:YES completion:nil];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self autoPlayVisibleVideo];
}

- (void)autoPlayVisibleVideo {
    NSArray *cells = self.tableView.visibleCells;
    DDDDrawBaseTableViewCell *cell =[cells objectAtIndex:0];
    if ([cell isKindOfClass:[DDDDrawBaseTableViewCell class]]) {
        NSInteger cellIndex = [(DDDDrawNormalTableViewCell *)cell videoId];
        NSInteger lastCellIndex = [_lastCell isKindOfClass:[DDDDrawNormalTableViewCell class]]?[(DDDDrawNormalTableViewCell *)_lastCell videoId]:200;
        if (cellIndex != lastCellIndex) {
            [(DDDDrawNormalTableViewCell *)cell autoPlay];
        }
    } else if ([_lastCell isKindOfClass:[DDDDrawNormalTableViewCell class]]){
        [(DDDDrawNormalTableViewCell *)_lastCell pause];
    }
    _lastCell = cell;
}

#pragma mark - DDDNativeExpressAdViewDelegate

/**
 * 当视图成功加载ad时的回调
 */
- (void)nativeExpressDrawAdSuccessToLoad:(DDDNativeExpressAdManager *)nativeExpressAd views:(NSArray<__kindof DDDNativeExpressAdView *> *)views {
    NSLog(@"%s",__func__);
    if (views.count) {
        NSMutableArray *dataSources = [self.dataSource mutableCopy];
        [views enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            DDDNativeExpressAdView *expressView = (DDDNativeExpressAdView *)obj;
            expressView.rootViewController = self;
            expressView.backgroundColor = [UIColor redColor];
//            [expressView configDataView];
            [expressView render];
            NSUInteger index = rand() % (self.dataSource.count-3)+2;
            [dataSources insertObject:expressView atIndex:index];
        }];
        self.dataSource = [dataSources copy];
    }
    [self.tableView reloadData];
}

/**
 * 当视图加载失败时的回调
 */
- (void)nativeExpressDrawAdFailToLoadError:(NSInteger)errorCode {
    NSLog(@"%s",__func__);
}


/**
 * 成功呈现nativeExpressAdView和nativeExpressAdView.size时调用此方法
 */
- (void)nativeExpressDrawAdViewRenderSuccess {
    NSLog(@"%s",__func__);
    [self.tableView reloadData];
}

/**
 * 此方法在nativeExpressAdView呈现失败时调用
 */
- (void)nativeExpressDrawAdViewRenderFailError:(NSInteger)errorCode {
    NSLog(@"%s",__func__);
}

/**
 * 当广告视图即将显示内容时发送
 */
- (void)nativeExpressDrawAdViewWillShow {
    NSLog(@"%s",__func__);
}

/**
 * 当一个广告视图被点击时发送
 */
- (void)nativeExpressDrawAdViewDidClick {
    NSLog(@"%s",__func__);
}

/**
 * 播放完成后的回调
 * @param errorCode : 对应错误码
 */
- (void)nativeExpressDrawAdViewPlayerDidPlayFinishError:(NSInteger)errorCode {
    NSLog(@"%s",__func__);
}

///**
// * Sent when a user clicked dislike reasons.
// * @param filterWords : the array of reasons why the user dislikes the ad
// */
//- (void)nativeExpressAdView:(DDDNativeExpressAdView *)nativeExpressAdView dislikeWithReason:(NSArray<DDDDislikeWords *> *)filterWords {
//    NSLog(@"%s",__func__);
//}


/**
 * 点击广告视图即将推出新视图时的回调
 */
- (void)nativeExpressDrawAdViewWillPresentScreen {
    NSLog(@"%s",__func__);
}


#pragma mark --- tableView dataSource&delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSUInteger index = indexPath.row;
    id model = self.dataSource[index];
    if ([model isKindOfClass:[DDDNativeExpressAdView class]]) {
        UITableViewCell *cell = nil;
        cell = [self.tableView dequeueReusableCellWithIdentifier:@"DDDNativeExpressCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        // 重用DDDNativeExpressAdView，先把之前的广告试图取下来，再添加上当前视图
        UIView *subView = (UIView *)[cell.contentView viewWithTag:1000];
        if ([subView superview]) {
            [subView removeFromSuperview];
        }
        
        UIView *view = model;
        view.tag = 1000;
        [cell.contentView addSubview:view];
        return cell;
    } else {
        DDDDrawNormalTableViewCell *cell = nil;
        cell = [tableView dequeueReusableCellWithIdentifier:@"DDDDrawNormalTableViewCell" forIndexPath:indexPath];
        cell.videoId = index;
        [cell refreshUIAtIndex:index];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [DDDDrawBaseTableViewCell cellHeight];
}

#pragma mark scrollviewDelegate

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self autoPlayVisibleVideo];
}



@end
